package com.linewow.xhyy.nihaonew.net.CallBack;

import com.google.gson.stream.JsonReader;
import com.linewow.xhyy.nihaonew.base.BaseEntity;
import com.linewow.xhyy.nihaonew.base.BaseInfo;
import com.linewow.xhyy.nihaonew.base.SimpleBaseEntity;
import com.linewow.xhyy.nihaonew.entity.NiHaoGeneral;
import com.linewow.xhyy.nihaonew.entity.baidu.BaiduInfo;
import com.linewow.xhyy.nihaonew.net.util.Convert;
import com.lzy.okgo.convert.Converter;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Response;

/**
 * ================================================
 * 作    者：jeasonlzy（廖子尧）Github地址：https://github.com/jeasonlzy0216
 * 版    本：1.0
 * 创建日期：16/9/11
 * 描    述：
 * 修订历史：
 * ================================================
 */
public class JsonConvert<T> implements Converter<T> {

    private Type type;

    public void setType(Type type) {
        this.type = type;
    }

    @Override
    public T convertSuccess(Response response) throws Exception {
        JsonReader jsonReader = new JsonReader(response.body().charStream());

        if (type == null) {
            //以下代码是通过泛型解析实际参数,泛型必须传
            Type genType = getClass().getGenericSuperclass();
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            type = params[0];
        }

        if (!(type instanceof ParameterizedType)) throw new IllegalStateException("没有填写泛型参数");
        Type rawType = ((ParameterizedType) type).getRawType();

//        //无数据类型
//        if (rawType == Void.class) {
//            SimpleResponse baseWbgResponse = Convert.fromJson(jsonReader, SimpleResponse.class);
//            //noinspection unchecked
//            return (T) baseWbgResponse.toLzyResponse();
//        }

        //有数据类型
        if (rawType == BaseInfo.class) {
            BaseInfo baseInfo= Convert.fromJson(jsonReader,type);
            return (T) baseInfo;
        }
        if(rawType== BaseEntity.class){
            BaseEntity baseEntity=Convert.fromJson(jsonReader,type);
            return (T) baseEntity;
        }
        if(rawType== BaiduInfo.class){
            BaiduInfo baiduInfo=Convert.fromJson(jsonReader,type);
            return (T) baiduInfo;
        }
        if(rawType== NiHaoGeneral.class){
            NiHaoGeneral niHaoGeneral=Convert.fromJson(jsonReader,type);
            return (T) niHaoGeneral;
        }
        if(rawType== List.class){
            List list=Convert.fromJson(jsonReader,type);
            return (T) list;
        }
        if(rawType== SimpleBaseEntity.class){
            SimpleBaseEntity simpleBaseEntity=Convert.fromJson(jsonReader,type);
            return (T) simpleBaseEntity;
        }

        throw new IllegalStateException("基类错误无法解析!");
    }
}